# coding=utf-8
from urllib import request

from service.basesv import BaseSV
from tools.beanret import BeanRet
from tools.cachedata import CacheData
from tools.cachedataclient import CacheDataClient


class LoginSV(BaseSV):
    def login(self, account, password):
        """
        登录 账户
         :param account: 账户
         :param password: 密码
         :return:
        :param account: 账户
        :param password: 密码
        :return:
        """
        try:
            response = request.urlopen(self.login_url.replace("{account}", account).replace("{password}", password))
            result = response.read()
            beanret = BeanRet().toObj(result)
            if beanret.success:
                cache_data_client = CacheDataClient()
                try:
                    cache_data = CacheData().toObj(cache_data_client.read())
                    if cache_data:
                        cache_data.token = beanret.getData
                        cache_data_client.write(cache_data.toJson())
                    else:
                        cache_data_client.write(CacheData(token=beanret.getData).toJson())
                except:
                    cache_data_client.write(CacheData(token=beanret.getData).toJson())

                return True
            else:
                return False
        except:
            return False
